/*
 * gArduino.c
 *
 * Created: 12/7/2013 8:31:03 PM
 *  Author: Hp-Minion
 */ 


#include <avr/io.h>
#include <avr/interrupt.h>

#include "General.h"
#include "Timer.h"
#include "USART_0.h"
#include "Port.h"
#include "Button.h"
#include "PWM.h"
#include "ADC.h"
#include "Temp_Hum.h"

/*****************************************************************************************/
void Initialisation(void);
void ledAlert(unsigned int time);
/*****************************************************************************************/
int main (void)
{
	StatusCodes GardenStatus = STATUS_CODE_UNDEFINED;
	
	// initialize context
	Context gardenContext = 
	    {
			0,                  /* systemClock */
			0,                  /* lifeTimer */
			{ 0, 0 },           /* soil */
			{ 0, 0 },           /* indoorAir */
			{ 0, 0 },           /* outdoorAir */
			0                   /* environmentLight */
		};
	
	Initialisation();
	
 	while(1) 
 	{
		if ( counter200 >= DAY_OVERFLOWS )
		{
			// 24 hours timer alarm
			counter200 = 0;
			
			DigitalWrite(5,HIGH);
			Delay_ms(1000);
			DigitalWrite(5,LOW);
			Delay_ms(1000);			
		}
		
		if (GardenStatus)
		{
			#ifdef MODULE_PRESENT_HUM_TEMP
		    GardenStatus = TempHum_Handler(IN_TEMP_HUM_PIN, &gardenContext.indoorAir);
			Delay_ms(500);
			#endif

			#ifdef MODULE_PRESENT_ADC_TEMP
			GardenStatus = ADC_Temp_Handler(SOIL_TEMP_PIN, &gardenContext.soil);
			Delay_ms(500);
			#endif
			
			#ifdef MUDULE_PRESENT_ADC_HUM
			GardenStatus = ADC_Hum_Handler(SOIL_MOISTURE_PIN, &gardenContext.soil);
			Delay_ms(500);
			#endif
			
			#ifdef MUDULE_PRESENT_ADC_LIGHT
			GardenStatus = ADC_Light_Handler(LIGHT_PIN, &gardenContext.environmentLight);
			Delay_ms(500);
			#endif
			
		}
		else
		{
			
		}
	}
 return 0;
}
/*****************************************************************************************/
void Initialisation(void)
{
	cli();
	
	PinMode(ARDUINO_LED,'D',OUTPUT);
	
	#ifdef DEBUG_LVL_0
	USART_InitUSART();
	#endif
	
	Init_timer2();
	
	#ifdef MODULE_PRESENT_HUM_TEMP
	TempHum_Init(IN_TEMP_HUM_PIN);
	#endif
	
	sei();
}
/*****************************************************************************************/
void ledAlert(unsigned int time)
{
	if (time == 0)
	{
	    time = ALERT_TIME;
	}
	
    DigitalWrite(ARDUINO_LED, HIGH);
	Delay_ms(time);
	DigitalWrite(ARDUINO_LED, LOW);
	Delay_ms(time);
}
/*****************************************************************************************/